import java.util.*;
/**
 * The class containing all important things for playing the game
 */
public class ScotlandYard {
	private Map map;
	private GUI gui;
	private boolean[] moved;
	private int turn;
	private Random random;

	public static void main(String[] args)
	{
		Random random = new Random();

		// Parse command-line arguments

		// Check for user-specified seed
		if (args.length > 0) {
			for(int i=0;i<args.length;i++)
			{
				if(args[i].equals("-s"))
					random = new Random(Integer.parseInt(args[++i]));
			}
		}

		// Start new game
		ScotlandYard sy = new ScotlandYard(random);
	}

	public ScotlandYard(Random random)
	{
		this.random = random;
		initialise();
	}

	public void initialise()
	{
		turn = 1;
		map = new Map(random);
		moved = new boolean[5];
		for (int i = 0; i < 5; i++) {
			moved[i] = false;
		}
		gui = new GUI(map, this);
	}

	public void move(int agent, Movement to) throws Exception {
		if (!moved[agent]) {
			// Set flag to prevent moving twice and move the agent.
			moved[agent] = true;
			map.agents[agent].moveToPosition(to);

			// Check if MrX has been captured or time is up
			boolean stopped = false;
			int again = 0;
			if (map.agents[agent].getPosition() == map.agents[5].getPosition()) {
				again = gui.win();
				stopped = true;
			}
			if (stopped) {
				if (again == 0) {
					initialise();
				} else {
					System.exit(0);
				}
			}

			if (detectivesHaveMoved()) {
				System.out.println("Moving Mr. X.");
				// move MrX.
				turn++;
				if (turn == 25) {
					again = gui.lose();
					stopped = true;
				}
				if (revealLocation()) {
					map.agents[5].makeVisible();
				} else {
					map.agents[5].makeInvisible();
				}
                System.out.println("Before move");
				map.agents[5].move();
                System.out.println("After move");

				// Set values to unmoved for this turn.
				for (int i = 0; i < 5; i++) {
					moved[i] = false;
				}
				System.out.println("Mr. X. moved.");

				// Did Mr. X. step on a Detective?
				if (map.agents[agent].getPosition() == map.agents[5].getPosition()) {
					again = gui.win();
					stopped = true;
				}
				if (stopped) {
					if (again == 0) {
						initialise();
					} else {
						System.exit(0);
					}
				}

			}
        gui.placeAgent(agent);
        //if(map.agents[5].isVisible())
            gui.placeAgent(5);
		} else {
            System.out.println("Trhowing exception");
			throw new Exception("Agent has already moved: Detective "+agent);
		}
	}

	private boolean detectivesHaveMoved()
	{
		boolean result = true;
		for (boolean b : this.moved) {
			result &= b;
		}
		return result;
	}

	private boolean revealLocation()
	{
		return (turn == 3 ||
				turn == 8 ||
				turn == 13 ||
				turn == 18 ||
				turn == 24);
	}

}
